<template>
	<view class="content">
		<view class="message-content">
			<view class="message-item" v-for="(item,i) in message_list" :key="i">

				<!-- 不是本用户显示位置 -->
				<view class="no-user-box" v-if="userFrom.openid != item.open_id">
					<view class="img-box">
						<view class="img">
							{{ slipName(item.name) }}
						</view>
					</view>
					<view class="message-box">
						<view class="title-box">
							<view class="name">
								{{item.name}}
							</view>
							<view class="time">
								{{timeSlip(item.create_date)}}
							</view>
						</view>
						<view class="message">
							{{item.neirong}}
						</view>
					</view>
				</view>
				<!-- 是本用户显示位置 -->
				<view class="user-box" v-if="userFrom.openid == item.open_id">

					<view class="message-box">
						<view class="title-box">
							<view class="name">
								{{item.name}}
							</view>
							<view class="time">
								{{timeSlip(item.create_date)}}
							</view>
						</view>
						<view class="message">
							{{item.neirong}}
						</view>
					</view>
					<view class="img-box">
						<view class="img">
							{{ slipName(item.name) }}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="input-box">
			<input class="input" type="text" focus v-model="userFrom.userInput" placeholder="请输入..." />
			<view class="send-btn" @click="sendMessge()">
				发送
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'

	import {
		timeRep
	} from '@/tools/tools.js'

	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'

	import {
		getGotoMessage,
		getSendMessageToTeam,
		getGotoMessageConversation
	} from '@/api/message_api.js'

	import {
		timeSlip
	} from '@/tools/tools.js'
	import mqtt from 'mqtt/dist/mqtt.js';

	const userFrom = reactive({
		userInput: '',
		teamId: '',
		telid: '',
		openid: ''
	})

	const mqttfrom = reactive({
		id: '',
		subscribe: '',
		connectTimeout: 10000,
		clean: true,
		mqttUrl: 'wxs://sanlimqtt.fun/mqtt',
	})
	const client = ref(null) // 用来存储客户端对象


	const message_list = ref([])

	const _getGotoMessage = (id) => {
		getGotoMessage(id).then((res) => {
			mqttfrom.subscribe = res.conversation_id.toString()
			mqttfrom.id = userFrom.openid
			console.log('会话信息1', res);
			message_list.value = res.liaotian_record
			userFrom.telid = res.conversation_id


			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 99999,
					duration: 300,
				});
				connectMqtt()
			}, 1000)
		})
	}

	const _getGotoMessageConversation = (id) => {
		getGotoMessageConversation(id).then((res) => {
			console.log('会话信息2', res);
			mqttfrom.id = userFrom.openid
			mqttfrom.subscribe = res.conversation_id.toString()
			message_list.value = res.liaotian_record
			userFrom.telid = res.conversation_id
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 99999,
					duration: 300,
				});
				connectMqtt()
			}, 1000)
		})
	}


	// 发送消息组件 开始发送
	const sendMessge = () => {
		if (userFrom.userInput !== '') {
			_getSendMessageToTeam()
		} else {

		}
	}

	// 发送消息组件	
	const _getSendMessageToTeam = () => {

		let data = {
			id: userFrom.telid,
			openid: userFrom.openid,
			message: userFrom.userInput
		}
		console.log(data);

		getSendMessageToTeam(data).then((res) => {
			userFrom.userInput = ''
		})
	}

	// mqtt 服务
	const connectMqtt = () => {

		let options = {
			clientId: mqttfrom.id,
			connectTimeout: 1000,
			clean: false
		}

		console.log('MQTT参数1', options, 'MQTT参数2', mqttfrom);

		client.value = mqtt.connect(mqttfrom.mqttUrl, options)

		client.value.on('connect', (res) => {

			console.log('MQTT，链接成功');

			// 只有在没有订阅时才订阅
			client.value.subscribe(mqttfrom.subscribe, (err) => {
				if (!err) {
					console.log('MQTT，消息订阅成功');
				} else {
					console.error('订阅失败', err);
				}
			});

		})

		client.value.on('message', (topic, message) => {
			console.log('MQTT，消息', topic, JSON.parse(message.toString()))

			dataList(JSON.parse(message.toString()))
		})

		client.value.on('reconnect', () => {
			console.log("MQTT，服务重连中")
		})


	}

	const slipName = (item) => {
		if (item) {
			return item.charAt(0);
		} else {

		}

	}

	const dataList = (item) => {
		let data = item.result[0]

		let itemdata = {
			create_date: data.create_date,
			name: data.name,
			neirong: data.neirong,
			open_id: data.open_id
		}


		message_list.value.push(itemdata)

		setTimeout(() => {
			uni.pageScrollTo({
				scrollTop: 999999999999999999,
				duration: 300,
			});
		}, 300)
		console.log(message_list.value);
	}

	onLoad((res) => {
		mqttfrom.id = timeRep()
		console.log('上层数据', res);
		uni.getStorage({
			key: 'openid',
			success: function(res2) {
				userFrom.openid = res2.data.openid
			}
		})

		if (res.check == 0) {
			userFrom.teamId = res.id
			_getGotoMessage(res.id)
		} else if (res.check == 1) {
			userFrom.telid = res.telid
			_getGotoMessageConversation(res.telid)
		}


	})

	const disconnectMQTT = () => {
		if (client.value) {
			client.value.end(true, () => {
				connectionStatus.value = '已断开';
				console.log('已断开连接');
			});
		}
	}



	// 页面卸载时断开MQTT连接
	onUnload(() => {
		disconnectMQTT();
	});
</script>

<style lang="scss" scoped>
	.content {
		background-color: #f5f5f5;
		min-height: calc(100vh - 180rpx);
		padding-bottom: 180rpx;

		.message-item {
			.no-user-box {
				display: flex;
				padding-top: 40rpx;

				.img-box {
					padding: 20rpx;

					.img {
						padding: 30rpx;
						text-align: center;
						border-radius: 10rpx;
						background-color: aliceblue;
					}
				}

				.message-box {

					.title-box {
						display: flex;
						justify-content: flex-start;

						.name {
							margin-right: 20rpx;
							max-width: 176px;
							/* 最大宽度 */
							white-space: nowrap;
							/* 禁止换行 */
							overflow: hidden;

							/* 隐藏溢出的文本 */
						}
					}

					.message {
						display: block;
						margin-top: 20rpx;
						padding: 20rpx;
						background-color: #ffffff;
						max-width: calc(100vw - 290rpx);
						border-radius: 10rpx;
					}
				}
			}

			.user-box {
				display: flex;
				padding-top: 40rpx;
				justify-content: flex-end;

				.img-box {
					padding: 20rpx;

					.img {
						padding: 30rpx;
						text-align: center;
						border-radius: 10rpx;
						background-color: aliceblue;
					}
				}

				.message-box {

					.title-box {
						display: flex;
						justify-content: flex-end;


						.name {
							margin-right: 20rpx;
							max-width: 176px;
							/* 最大宽度 */
							white-space: nowrap;
							/* 禁止换行 */
							overflow: hidden;

							/* 隐藏溢出的文本 */
						}
					}

					.message {
						display: block;
						margin-top: 20rpx;
						padding: 20rpx;
						background-color: #95ec69;
						max-width: calc(100vw - 290rpx);
						border-radius: 10rpx;
						line-height: 43rpx;
					}
				}
			}
		}

		.input-box {
			position: fixed;
			bottom: 0px;
			left: 0px;
			right: 0px;
			width: 100vw;
			padding: 20rpx 20rpx 60rpx 20rpx;
			background-color: white;
			display: flex;

			.input {
				padding: 20rpx;
				border-radius: 20rpx;
				background-color: #f3f5f6;
				width: calc(100vw - 200rpx);
				margin-right: 20rpx;
			}

			.send-btn {
				color: white;
				background-color: skyblue;
				padding: 22rpx;
				border-radius: 20rpx;
			}
		}
	}
</style>